"use client"

import { useEffect, useState } from "react"
import { TicketTemplate, TemplateStep } from "@/types/template"
import { useAdminStore } from "@/lib/store"
import { Button } from "@/components/ui/button"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
  FormDescription,
} from "@/components/ui/form"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import * as z from "zod"
import { 
  Table, 
  TableBody, 
  TableCell, 
  TableHead, 
  TableHeader, 
  TableRow 
} from "@/components/ui/table"
import { Checkbox } from "@/components/ui/checkbox"
import { 
  DragDropContext, 
  Droppable, 
  Draggable,
  DropResult,
  DroppableProvided,
  DraggableProvided
} from "@hello-pangea/dnd"
import { Grip, Plus, Trash2 } from "lucide-react"

const formSchema = z.object({
  name: z.string().min(1, "模板名称不能为空"),
  type: z.string().min(1, "票种类型不能为空"),
  description: z.string().min(1, "描述不能为空"),
  location: z.string().min(1, "位置不能为空"),
  taskName: z.string().min(1, "任务名称不能为空"),
  target: z.string().min(1, "目标股道不能为空"),
  conditions: z.string().min(1, "作业条件不能为空"),
  requiredGear: z.string().min(1, "必备装备不能为空"),
  precautions: z.string().min(1, "注意事项不能为空"),
})

type FormValues = z.infer<typeof formSchema>

interface TemplateDialogProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  template?: TicketTemplate
}

export function TemplateDialog({
  open,
  onOpenChange,
  template,
}: TemplateDialogProps) {
  const { addTemplate, updateTemplate } = useAdminStore()
  const isEditing = !!template
  
  // 步骤管理
  const [steps, setSteps] = useState<TemplateStep[]>([])
  const [newStepDescription, setNewStepDescription] = useState("")
  const [newStepIsCritical, setNewStepIsCritical] = useState(false)

  const form = useForm<FormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: template?.name || "",
      type: template?.type || "",
      description: template?.description || "",
      location: template?.location || "丁堰车辆段",
      taskName: template?.task?.name || "",
      target: template?.task?.target || template?.task?.name?.split(" ")[0] || "",
      conditions: template?.task?.conditions || "",
      requiredGear: template?.task?.requiredGear?.join(", ") || "",
      precautions: template?.task?.precautions?.join("\n") || "",
    },
  })

  useEffect(() => {
    if (open) {
      if (template) {
        form.reset({
          name: template.name,
          type: template.type,
          description: template.description,
          location: template.location,
          taskName: template.task.name,
          target: template.task.target || template.task.name.split(" ")[0] || "",
          conditions: template.task.conditions,
          requiredGear: template.task.requiredGear.join(", "),
          precautions: template.task.precautions.join("\n"),
        })
        setSteps(template.steps || [])
      } else {
        form.reset({
          name: "",
          type: "",
          description: "",
          location: "丁堰车辆段",
          taskName: "",
          target: "",
          conditions: "",
          requiredGear: "",
          precautions: "",
        })
        setSteps([])
      }
      setNewStepDescription("")
      setNewStepIsCritical(false)
    }
  }, [open, template, form])

  const onSubmit = (values: FormValues) => {
    // 处理任务名称，确保包含目标股道
    const taskName = values.taskName.includes(values.target) 
      ? values.taskName 
      : `${values.target} ${values.taskName}`

    const templateData: Partial<TicketTemplate> = {
      name: values.name,
      type: values.type,
      description: values.description,
      location: values.location,
      task: {
        name: taskName,
        target: values.target,
        conditions: values.conditions,
        requiredGear: values.requiredGear.split(",").map(item => item.trim()),
        precautions: values.precautions.split("\n").map(item => item.trim()).filter(item => item !== ""),
      },
      steps: steps.map((step, index) => ({
        ...step,
        stepNumber: index + 1
      })),
    }

    if (isEditing && template) {
      updateTemplate(template.id, templateData)
    } else {
      // 新建模板
      addTemplate(templateData as TicketTemplate)
    }

    onOpenChange(false)
  }

  // 添加新步骤
  const addStep = () => {
    if (!newStepDescription.trim()) return

    const newStep: TemplateStep = {
      stepNumber: steps.length + 1,
      description: newStepDescription,
      ...(newStepIsCritical && { isCritical: true })
    }

    setSteps([...steps, newStep])
    setNewStepDescription("")
    setNewStepIsCritical(false)
  }

  // 删除步骤
  const deleteStep = (index: number) => {
    const newSteps = [...steps]
    newSteps.splice(index, 1)
    setSteps(newSteps.map((step, idx) => ({ ...step, stepNumber: idx + 1 })))
  }

  // 处理拖放排序
  const handleDragEnd = (result: DropResult) => {
    if (!result.destination) return

    const items = Array.from(steps)
    const [reorderedItem] = items.splice(result.source.index, 1)
    items.splice(result.destination.index, 0, reorderedItem)

    setSteps(items.map((item, index) => ({ ...item, stepNumber: index + 1 })))
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-[800px] max-h-[90vh] overflow-y-auto">
        <DialogHeader>
          <DialogTitle>{isEditing ? "编辑操作票模板" : "新增操作票模板"}</DialogTitle>
          <DialogDescription>
            {isEditing
              ? "修改操作票模板信息，点击保存确认更改。"
              : "添加新操作票模板，填写信息后点击创建。"}
          </DialogDescription>
        </DialogHeader>
        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-6">
            <div className="space-y-4">
              <h3 className="text-lg font-medium">基本信息</h3>
              
              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="name"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>模板名称</FormLabel>
                      <FormControl>
                        <Input placeholder="如：隔离开关合闸操作票 (送电) - 标准模板" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="type"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>票种类型</FormLabel>
                      <FormControl>
                        <Input placeholder="如：隔离开关合闸操作票 (送电)" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>

              <FormField
                control={form.control}
                name="description"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>模板描述</FormLabel>
                    <FormControl>
                      <Textarea 
                        placeholder="输入模板描述" 
                        className="resize-none" 
                        {...field} 
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="location"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>位置</FormLabel>
                    <FormControl>
                      <Input placeholder="如：丁堰车辆段" {...field} />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className="space-y-4">
              <h3 className="text-lg font-medium">任务信息</h3>
              
              <div className="grid grid-cols-2 gap-4">
                <FormField
                  control={form.control}
                  name="target"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>目标股道</FormLabel>
                      <FormControl>
                        <Input placeholder="如：21股道" {...field} />
                      </FormControl>
                      <FormMessage />
                    </FormItem>
                  )}
                />

                <FormField
                  control={form.control}
                  name="taskName"
                  render={({ field }) => (
                    <FormItem>
                      <FormLabel>任务名称</FormLabel>
                      <FormControl>
                        <Input placeholder="如：隔离开关送电" {...field} />
                      </FormControl>
                      <FormDescription>
                        会自动与目标股道组合，如"21股道 隔离开关送电"
                      </FormDescription>
                      <FormMessage />
                    </FormItem>
                  )}
                />
              </div>



              <FormField
                control={form.control}
                name="conditions"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>作业条件</FormLabel>
                    <FormControl>
                      <Textarea 
                        placeholder="输入作业条件" 
                        className="resize-none" 
                        {...field} 
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="requiredGear"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>必备装备</FormLabel>
                    <FormControl>
                      <Input 
                        placeholder="用逗号分隔，如：安全帽, 绝缘手套, 绝缘鞋" 
                        {...field} 
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />

              <FormField
                control={form.control}
                name="precautions"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>注意事项</FormLabel>
                    <FormControl>
                      <Textarea 
                        placeholder="每行一条注意事项" 
                        className="resize-none min-h-[100px]" 
                        {...field} 
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            </div>

            <div className="space-y-4">
              <h3 className="text-lg font-medium">操作步骤</h3>
              <p className="text-sm text-muted-foreground">
                添加操作步骤，可拖动调整顺序。步骤编号会自动生成。
              </p>

              {/* 步骤列表 */}
              <div className="border rounded-md">
                <DragDropContext onDragEnd={handleDragEnd}>
                  <Droppable droppableId="steps">
                    {(provided: DroppableProvided) => (
                      <Table>
                        <TableHeader>
                          <TableRow>
                            <TableHead className="w-[60px]">序号</TableHead>
                            <TableHead>步骤描述</TableHead>
                            <TableHead className="w-[100px]">关键步骤</TableHead>
                            <TableHead className="w-[80px]">操作</TableHead>
                          </TableRow>
                        </TableHeader>
                        <TableBody {...provided.droppableProps} ref={provided.innerRef}>
                          {steps.map((step, index) => (
                            <Draggable key={index} draggableId={`step-${index}`} index={index}>
                              {(provided: DraggableProvided) => (
                                <TableRow 
                                  ref={provided.innerRef}
                                  {...provided.draggableProps}
                                >
                                  <TableCell className="font-medium">
                                    <div className="flex items-center">
                                      <div 
                                        {...provided.dragHandleProps}
                                        className="mr-2 cursor-grab"
                                      >
                                        <Grip className="h-4 w-4" />
                                      </div>
                                      {step.stepNumber}
                                    </div>
                                  </TableCell>
                                  <TableCell>{step.description}</TableCell>
                                  <TableCell className="text-center">
                                    {step.isCritical ? "是" : "否"}
                                  </TableCell>
                                  <TableCell>
                                    <Button
                                      variant="ghost"
                                      size="sm"
                                      onClick={() => deleteStep(index)}
                                    >
                                      <Trash2 className="h-4 w-4 text-red-500" />
                                    </Button>
                                  </TableCell>
                                </TableRow>
                              )}
                            </Draggable>
                          ))}
                          {provided.placeholder}
                        </TableBody>
                      </Table>
                    )}
                  </Droppable>
                </DragDropContext>
              </div>

              {/* 添加步骤 */}
              <div className="flex items-end gap-2">
                <div className="flex-1">
                  <label className="text-sm font-medium">步骤描述</label>
                  <Input
                    value={newStepDescription}
                    onChange={(e) => setNewStepDescription(e.target.value)}
                    placeholder="输入步骤描述"
                  />
                </div>
                <div className="w-[120px] flex flex-col">
                  <label className="text-sm font-medium mb-2">关键步骤</label>
                  <div className="flex items-center space-x-2">
                    <Checkbox
                      id="isCritical"
                      checked={newStepIsCritical}
                      onCheckedChange={(checked) => setNewStepIsCritical(!!checked)}
                    />
                    <label
                      htmlFor="isCritical"
                      className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                    >
                      是
                    </label>
                  </div>
                </div>
                <Button type="button" onClick={addStep}>
                  <Plus className="h-4 w-4 mr-1" /> 添加
                </Button>
              </div>
            </div>

            <DialogFooter>
              <Button type="submit">
                {isEditing ? "保存" : "创建"}
              </Button>
            </DialogFooter>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  )
} 